<template>
	<view class="content">
		<view v-show="messages.length == 0" class="chat-logo">
			<image class="logo" src="/static/start/Asset.png"></image>
			<view class="text-area">
				<text class="title">{{title}}</text>
			</view>
		</view>
		<view class="uni-list-cell">
			<view class="uni-list-cell-db">
				<picker @change="bindPickerChange" :value="index" :range="modelArray">
					<view class="uni-input">{{modelArray[index]}}</view>
				</picker>
			</view>
		</view>
		<scroll-view scroll-with-animation :scroll-into-view="item" :scroll-top="scrollTop" class="Scroll" scroll-y="true"
			>
		<view class="chat-container" id="chat-container" v-show="messages.length !== 0">
			
			<view v-for="(message, index) in messages" :key="index" :id="`item-${index}`"
				:class="message.align === 'left' ? 'message-left' : 'message-right'">
				<view class="name">
					<image v-if="message.align === 'left'" src="../../static/index/aislogo.png" style="width: 20px;height: 20px;"></image>
					
					<span>{{ message.name }}
					</span>
					<image v-if="message.align === 'right'" src="../../static/index/people.png" style="width: 20px;height: 20px;float: right;"></image>
					
				</view>
				<ua-markdown class="chat_message" :source="message.text" />
				<image @click="copyText(message.text)" src="../../static/index/copy.png" :class="message.align === 'left' ? 'copy-left' : 'copy-right'"></image>
			</view>
			<view v-show="guessList.length !== 0" class="guess_father">
				
				<view v-for="(item, index) in guessList" :key="index" style="margin: 12px 0px;">
					<span class="guess-item" @click="chatWithQues(item)">{{ item }}</span>
				</view>
			</view>
			<view class="chat_genr" v-show="aichat">
				<image src="../../static/index/loading.png" style="width: 20px;height: 20px;"></image> Bot AI生成中...
				<view class="loading">
					<svg width="64px" height="48px">
						<polyline points="0.157 23.954, 14 23.954, 21.843 48, 43 0, 50 24, 64 24" id="back"></polyline>
						<polyline points="0.157 23.954, 14 23.954, 21.843 48, 43 0, 50 24, 64 24" id="front"></polyline>
					</svg>

				</view>

			</view>
			<!-- <view v-show="aichat" class="chat-stop" style="text-align: center;">
				<el-button @click="stopchat">停止回答</el-button>
			</view> -->
			<view class="chat-bottom"></view>
		</view>
		
		</scroll-view>
		
		<view class="chat-footer" id="chat-footer">
			<div class="footer-left">
				<input id="textArea" v-model="sendmsg" placeholder="是不是想问点什么？" />
			</div>
			<view class="footer-right" @click="sendmsgClick">
				<image src="/static/index/send.png"></image>
			</view>
		</view>
	</view>
</template>
<script setup>
	import {
		ref,
		watch,
		nextTick,
		getCurrentInstance,
		 onMounted
	} from 'vue'
	import {
		onReady,
		onLoad
	} from '@dcloudio/uni-app'
	// scroll-into-view指向的id值
	let item = ref('')
	
	let scrollTop = ref(0)
	const modelArray = ref(['qwen-plus','qwen-turbo','qwen-max'])
	const instance = getCurrentInstance();

	const sendmsg = ref('')
	const title = ref('你好！欢迎访问Lizer Chat，有什么问题可以问我哦！')
	const messages = ref([ ])
	const guessList = ref([])
	const historyList = ref([])
	const aichat = ref(false)
	let controller = null //在外面定一个控制器,设置为空 
	const isStart = ref(true)
	const maxScrollHeight = ref(0)
	// 动态更新item的值
	watch(messages,(newval,oldval)=>{
		// 重新赋值item,延迟到dom更新之后进行，否则没效果
		nextTick(()=>{
			item.value = "item-" + (newval.length - 1)
			//  const query = uni.createSelectorQuery()
			// query.select('.Scroll').boundingClientRect()
			// query.select('.chat-container').boundingClientRect()
			// query.exec(res => {
			//   const scrollViewHeight = res[0].height
			//   const scrollContentHeight = res[1].top
			//   let scrollHeight = scrollViewHeight - scrollContentHeight;
			//   if(maxScrollHeight.value < scrollHeight) {
			//   	console.log(scrollHeight,'scrollHeight')
			//   	maxScrollHeight.value = scrollHeight
			//   	scrollTop.value = scrollHeight
			//   }
			// })
			// loadScrollTop()
			
			
		})
		
		
	},{
		deep:true, //深度监视
		immediate:true //初始化立即执行
	})	
	
	
	const index = ref(0)
	
	const modelName = ref('')

	
	function bindPickerChange(e) {
		console.log('picker发送选择改变，携带值为', e.detail.value)
		index.value = e.detail.value
		modelName.value = modelArray.value[index.value]
	}
	
	function copyText(val) {
		uni.setClipboardData({
		    data: val, // e是你要保存的内容
		    success: function () {
				uni.showToast({
					title:'复制成功',
					icon:'none'
				})
		    }
		})
	}
	
	function loadScrollTop(){
			const query = uni.createSelectorQuery().in(instance.proxy);
			query
			  .select(".chat-bottom")
			  .boundingClientRect((data) => {
				  if(maxScrollHeight.value < data.top) {
				  	maxScrollHeight.value = data.top
				  	scrollTop.value = data.top
				  }  
			  })
			  .exec();
	}
	
	
	function stopchat() {
	  // 在需要的时候中止请求
	  controller.abort();
	  isStart.value = true
	  aichat.value = false
	}
	
	function chatWithQues(msg) {
	  if(msg.indexOf('.') != -1){
	    msg = msg.split('.')[1]
	  }
	  sendmsg.value = msg
	  sendmsgClick()
	}
	
	function sendmsgClick() {
		if (!sendmsg.value) {
			ElMessage.error("请输入消息")
			return
		}
		guessList.value = []
		historyList.value.push({
			"role": "user",
			"content": sendmsg.value
		})
		messages.value.push({
			text: sendmsg.value,
			align: "right",
			name: "我"
		})
		sendmsg.value = ''
		robotReplay()
	}
	
	async function genQuestion() {
	  historyList.value.push({"role": "user","content": '请根据上一次你的回答生成3个问题,只要问题,不要任何其他修饰语言！'})
	  const requestBody = {
	    "messages": historyList.value.slice(-10),
	    "stream": false,
		 'model':modelName.value,
	  }
	  const requestTask = uni.request({
	  	url: 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions',
	  	timeout: 15000,
	  	responseType: 'text',
	  	method: 'POST',
	  	header: {
	  		'Content-Type': 'application/json',
	  		'Authorization': "Bearer sk-d6c7874f63c14171a0c66f766795f782",
	  	},
	  	data: JSON.stringify(requestBody),
	  	success: async response => {
			guessList.value = response.data.choices[0].message.content.split('\n')
			historyList.value.pop()
			loadScrollTop()
	  	},
	  	fail: error => {}
	  })
	  
	}

	async function robotReplay() {
		const requestData = []
		const obj = {
			text: sendmsg.value,
			type: 'text'
		}
		requestData.push(obj)

		//  if (controller) {
		// controller.abort()
		// controller = null
		//  }
		//  //没有的话就到这一步
		//  controller = new AbortController()

		// isStart.value = false
		// 获取数组的第一个对象
		let firstMessage = historyList.value[0];
		
		// 获取数组的最后10个对象
		let last10Messages = historyList.value.slice(-10);
		
		// 组合成一个包含第一个对象和最后10个对象的数组
		// let messages = [firstMessage, ...last10Messages];
		const requestBody = {
			"messages": [firstMessage, ...last10Messages],
			"stream": true,
			'model':modelName.value,
		}
		const requestTask = uni.request({
			url: 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions',
			timeout: 15000,
			responseType: 'text',
			method: 'POST',
			header: {
				'Content-Type': 'application/json',
				'Authorization': "Bearer sk-d6c7874f63c14171a0c66f766795f782",
			},
			enableChunked: true, //配置这里
			data: JSON.stringify(requestBody),
			success: async response => {
				// console.log(response, 'res')
			},
			fail: error => {}
		})

		requestTask.onChunkReceived(function(res) {
			// 获取最后一条消息
			const lastMessage = messages.value[messages.value.length - 1];
			// 处理接收到的数据块
			let decoder = new TextDecoder('utf-8');
			let text = decoder.decode(new Uint8Array(res.data));
			// if (text.indexOf(': ping') !== -1) {
				
			// }
			// 打印第一块的文本内容
			// const responseJson = JSON.parse(text.substr(5));
			// console.log(text,'text');

			// 使用 split 方法分割字符串，支持处理一个或多个 JSON 数据块
			const responses = text.split(/\ndata: /).filter(Boolean);
			responses.forEach(response => {
				try {
					// 去掉前缀 'data: ' 并解析为 JSON 对象
					const trimmedResponse = response.trim().replace(/^data:\s*/, '');
					const responseJson = JSON.parse(trimmedResponse);
					// 在这里处理 responseJson，例如处理 choices 中的数据
					const content = responseJson.choices[0].delta.content;
					// if (content.match(/[。？！，：]/)) { // 匹配字符分割
					// 	// console.log(lastMessage.text, 'text');

					// 	const sentences = lastMessage.text.split(/[。？！，：]/); //  匹配字符分割
					// 	sentences.forEach(async sentence => {
					// 		const trimmedSentence = sentence.trim();
					// 		if (trimmedSentence !== '' && !processedSentences.includes(
					// 				trimmedSentence)) {
					// 			processedSentences.push(trimmedSentence); // 将句子加入已处理列表
					// 			await speech(trimmedSentence);
					// 		}
					// 	});
					// }
					if(content == '') {
						return
					}
					if (lastMessage && lastMessage.name === "Bot AI") {
						lastMessage.text += content;
					} else {
						// 否则创建新的消息记录
						messages.value.push({
							text: content,
							align: "left", // 假设 AI 回复左对齐
							name: "Bot AI",
						});
						aichat.value = true
					}
					loadScrollTop()

					// console.log(responseJson);
				} catch (error) {
					// console.error('解析 JSON 出错:', error);
					// 可以添加错误处理逻辑，比如记录日志或者其它处理
				}
			});
			
			// 将数据块渲染到组件
			if (text.indexOf('DONE') !== -1) {
				aichat.value = false
				isStart.value = true
				historyList.value.push({
					"role": "assistant",
					"content": lastMessage.text
				})
				genQuestion()
				loadScrollTop()
				return
			}
		});
	}
	
	onMounted(() => {
		// messages.value.push({
		// 	text: content,
		// 	align: "left", // 假设 AI 回复左对齐
		// 	name: "Bot AI",
		// });
		// historyList.value.push({
		// 	"role": "assistant",
		// 	"content": lastMessage.text
		// })
		modelName.value = modelArray.value[index.value]
	})
	onLoad((option) => { //option为object类型，会序列化上个页面传递的参数
			if(option.text !== '' && option.text !== undefined && option.text !== null){
				messages.value.push({
					text: option.text,
					align: "left", // 假设 AI 回复左对齐
					name: "Bot AI",
				});
				historyList.value.push({
					"role": "system",
					"content": option.text + '你必须严格的执行这个命令，如果遇到不相关的问题，就请回答请问我相关的问题。'
				})
			}
		})
	onReady(() => {
		console.log('onReady')
	})
</script>


<style lang="scss">
	.guess_father{
		font-size: 12px;
	}
	.guess-item{
	    margin: 10px 0px;
	    //width: auto;
	    box-sizing: border-box;
	    color: var(--txt_icon_black_1, #1a2029);
	    font-family: PingFang SC;
	    font-size: 13px;
	    font-style: normal;
	    font-weight: 600;
	    line-height: 20px;
	    text-align: left;
	    cursor: pointer;
	    border: 1px solid transparent;
	    // display: flex;
	    padding: 9px 12px 9px 15px;
		white-space: nowrap;
		text-overflow: ellipsis;
		overflow: hidden;
	    // align-items: center;
	    gap: 8px;
	    border-radius: 12px;
		text-decoration: underline;
	    // background: var(--hover_icon_grey_1, rgba(79, 88, 102, .06));
	}
	.ua__markdown {
		padding: 20px 12px;
		// background: #f8f8f9;
		margin-bottom: 15px;
		word-wrap: break-word;
		font-weight: 400;
		font-size: 14px;
		color: #303133;
		margin-bottom: 0px !important;
	}

	.message-left {
		max-width: 418px;
		align-self: flex-start;
		width: 80%;
		position: relative;
		.copy-left{
			position: absolute;
			top: 20px;
			right: -25px;
			width: 20px;
			height: 20px;
		}
		.ua__markdown {
			// background-image: url('../../static/index/leftMsg.png');
			background-color: #f5f5f5;
			border-radius: 20px 20px 20px 0px;
			background-size: 100% 100%;
			color: black;
		}


		.name {
			font-size: 10px;
			align-self: flex-start;
		}
	}

	.message-right {
		max-width: 418px;
		align-self: flex-end;
		display: flex;
		flex-direction: column;
		width: 80%;
		position: relative;
		.copy-right{
			position: absolute;
			top: 20px;
			left: -25px;
			width: 20px;
			height: 20px;
		}
		.ua__markdown {
			// background-image: url('../../static/index/rightMsg.png');
			background-color: #17c3ce;
			border-radius: 20px 20px 0px 20px;
			background-size: 100% 100%;
			color: white;
		}

		.name {
			font-size: 10px;
			align-self: flex-end;
		}
	}

	.chat-container {
		width: 100%;
		height: calc(100vh - 150px);
		display: flex;
		flex-direction: column;
		padding: 20px;
		box-sizing: border-box;
		.name{
			display: flex;
			align-items: center;
		}
		// overflow: auto;
	}

	.content {
		// display: flex;
		// flex-direction: column;
		// align-items: center;
		// justify-content: center;
		width: 100%;
		height: 100vh;
		// padding: 20px 20px;
		box-sizing: border-box;
		/* background-color: red; */
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
		width: 90%;
		text-align: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}

	.chat-footer {
		position: absolute;
		bottom: constant(safe-area-inset-bottom);
		bottom: env(safe-area-inset-bottom);
		width: 90%;
		display: flex;
		height: 50px;
		justify-content: space-around;
		margin-bottom: 10px;
		margin: 0 auto;
		left: 50%;
		transform: translateX(-50%);
		.footer-left {
			width: 80%;
			height: 50px;
			background-color: #fafafa;
			border-radius: 10px;
			box-shadow: 1px 1px 3px 1px #eee;
			display: flex;
			align-items: center;
			justify-content: center;
			input{
				font-size: 12px;
				font-family: PingFang SC;
				height: 60rpx;
				line-height: 60rpx;
				width: 100%;
				&::placeholder {
				  line-height: normal; /* 或者设置一个具体值 */
				  vertical-align: middle;
				  height: 60rpx;
				  line-height: 60rpx;
				  height: 100%;
				}
			}
		}

		.footer-right {
			width: 20%;
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			background-color: #17c3ce;
			max-width: 50px;
			width: 40px;
			height: 40px;
			padding: 5px;

			image {
				width: 30px;
				height: 30px;
			}
		}
	}
	.loading svg polyline {
	  fill: none;
	  stroke-width: 3;
	  stroke-linecap: round;
	  stroke-linejoin: round;
	}
	
	.loading svg polyline#back {
	  fill: none;
	  stroke: #ff4d5033;
	}
	
	.loading svg polyline#front {
	  fill: none;
	  stroke: #ff4d4f;
	  stroke-dasharray: 48, 144;
	  stroke-dashoffset: 192;
	  animation: dash_682 1.4s linear infinite;
	}
	
	@keyframes dash_682 {
	  72.5% {
	    opacity: 0;
	  }
	
	  to {
	    stroke-dashoffset: 0;
	  }
	}
	.chat_genr {
	  display: flex;
	  align-items: center;
	  margin-left: 30px;
	  color: gainsboro;
	}
	.chat-logo{
		display: flex;
		align-items: center;
		flex-direction: column;
		justify-content: center;
	}
	.uni-list-cell{
		margin-top: 10px;
		display: flex;
		align-items: center;
		justify-content: center;
		height: 30px;
		.uni-input{
			text-align: center;
			padding: 10px;
			width: 100px;
			background-color: #17c3ce;
			border-radius: 7px;
			color: white;
			margin: 0px 10px;
			// text-decoration: underline;
		}
	}
</style>